import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Ap0stoL2
 * Date: 2023-08-02
 * Time: 21:29
 */

//使用原子类
public class Demo26 {
    //自增器
    private  static AtomicInteger count = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        //t1和t2线程就不需要 加锁,应为count自增是原子的了,原来要加锁是应为count是 先load ,再 ++,再save这就导致不是原子操作
        Thread t1 = new Thread(()->{
            for(int i=0;i<50000;i++){
                //count++
                count.getAndIncrement();//java不支持运算符重载
                //++count
                //count.incrementAndGet();

                //count--
                //count.getAndDecrement();
                //--count
                //count.decrementAndGet();
            }
        },"t1");

        Thread t2 = new Thread(()->{
            for(int i=0;i<50000;i++){
                //count++
                count.getAndIncrement();//java不支持运算符重载
                //++count
                //count.incrementAndGet();

                //count--
                //count.getAndDecrement();
                //--count
                //count.decrementAndGet();
            }
        },"t2");


        t1.start();
        t2.start();
        t1.join();//不阻塞,main线程会跑完
        t2.join();

        System.out.println(count.get()); //获取到原子类原始的数值
    }
}
